package com.peiwan.user.service.impl;

import com.peiwan.user.dto.LoginDTO;
import com.peiwan.user.dto.TokenDTO;
import com.peiwan.user.dto.UserDTO;
import com.peiwan.user.service.AuthService;
import com.peiwan.user.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Service
public class AuthServiceImpl implements AuthService {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final String jwtSecret;

    public AuthServiceImpl(UserService userService, 
                         PasswordEncoder passwordEncoder,
                         @Value("${jwt.secret}") String jwtSecret) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.jwtSecret = jwtSecret;
    }

    @Override
    public TokenDTO login(LoginDTO loginDTO) {
        // 验证用户
        UserDTO user = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        
        // 生成JWT令牌
        SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
        String token = Jwts.builder()
                .setSubject(user.getUsername())
                .claim("permission", user.getPermission())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24小时
                .signWith(key)
                .compact();
                
        return new TokenDTO(token, user);
    }
}